package com.duing.service.impl;

import com.duing.config.Commons;
import com.duing.config.bean.RankBean;
import com.duing.dao.BookshelfMapper;
import com.duing.entity.Bookshelf;
import com.duing.service.BookShelfService;
import com.duing.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

@Service
public class BookShelfServiceImpl implements BookShelfService {

    @Autowired
    private BookshelfMapper bookshelfMapper;

    @Autowired
    private RedisUtil redisUtil;
    @Override
    public boolean collect(String userId, String bookId) {
        Bookshelf bookshelf = bookshelfMapper.selectByUserAndBook(userId, bookId);
        return bookshelf != null;
    }

    @Override
    public boolean toCollect(String userId, String bookId) {

        Boolean isCollect = collect(userId, bookId);
        if (isCollect) return true;

        // mysql
        Bookshelf bookshelf = new Bookshelf();
        bookshelf.setUserId(userId);
        bookshelf.setBookId(bookId);
        int flag = bookshelfMapper.insert(bookshelf);

        String key = bookId + Commons.FAV_NUM;
        if (!redisUtil.hasKey(key)) {
            redisUtil.set(key, "1");
        } else {
            redisUtil.incr(key);
        }
        return flag == 1;
    }

    public void rank() {
        String pattern = "*" + Commons.FAV_NUM;
        Set<String> set = redisUtil.getKeys(pattern);
        List<RankBean> list = new ArrayList<>();
        for (String s : set) {
            int num = (int) redisUtil.get(s);
            RankBean rankBean = new RankBean(s, num);
            list.add(rankBean);
        }

        Collections.sort(list);
    }

}
